#include "strategies/OppSuitTrackDiscardStrategy.h"
#include "Query.h"

int OppSuitTrackDiscardStrategy::pickDiscard(CCardStack* hand, bool lastCardPicked, const GameState* gameState) {
    int ret = 0;
    int otherPlayer = (gameState->getCurrPlayer() + 1) % 2;
    // Find the history of the suits in hand
    CCardStack cardsBySuit[4];
    vector<int> suitsInHand;
    int handRange = lastCardPicked ? 3 : 4;
    for (int i = 0; i < handRange; i++) {
        int cardSuit = hand->at(i).Suit();
        if (cardsBySuit[cardSuit].Size() == 0) {
            suitsInHand.push_back(cardSuit);
        }
        cardsBySuit[cardSuit].Push(CCard(hand->at(i).GetIndex()));
    }
    int handSuitHistory[suitsInHand.size()];
    for (unsigned int i = 0; i < suitsInHand.size(); i++) {
        handSuitHistory[i] = gameState->suitHistory[otherPlayer][suitsInHand[i]];
    }
    // Find the suit with best history (most discarded), and the number of ties for decision certainty
    int bestSuitIndex = Query::minValueIndex(handSuitHistory, suitsInHand.size());
    numTies = 0;
    for (unsigned int i = 0; i < suitsInHand.size(); i++) {
        if (handSuitHistory[i] == handSuitHistory[bestSuitIndex]) {
            numTies++;
        }
    }
    decisionCertainty = 100 / numTies;
    // Find the minimum value card of that suit
    int bestSuit = suitsInHand[bestSuitIndex];
    if (cardsBySuit[bestSuit].Size() > 0) {
        CCard toDiscard = cardsBySuit[bestSuit].at(0);
        if (cardsBySuit[bestSuit].Size() > 1) {
            toDiscard = Query::minValueCard(cardsBySuit[bestSuit]);
        }
        if (!toDiscard.IsJoker()) {
            for (int i = 0; i < handRange; i++) {
                if (hand->at(i).GetIndex() == toDiscard.GetIndex()) {
                    ret = i;
                    break;
                }
            }
        }
        else {
            decisionCertainty = 0;
        }
    }
    else {
        decisionCertainty = 0;
    }
    return ret;
}
